/**
 * @author:稀饭
 * @time:上午12:00:19
 * @filename:Work.java
 */
package service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import util.ConnectionUtil;
import data.Data;

public class Work_rice {
	// 預線程數
	private static int corePoolSize = 5;
	// 開啟的最大線程數
	private static int maximumPoolSize = 10;
	// 空閒線程存活時間
	private static long keepAliveTime = 3;
	private static ThreadPoolExecutor threadPool = null;
	private static BlockingQueue<Runnable> linkedBlockingQueue = null;

	public static void main(String[] args) {
		setThreadPool();
		ArrayList<String> list = work();
		for (int i = 0; i < list.size(); i++) {
			DownThread downThread = new DownThread(Data.url + list.get(i));
			//System.out.println(Data.url + list.get(i));
			threadPool.execute(downThread);
		}
		threadPool.shutdown();
	}

	// 開啟線程池
	public static void setThreadPool() {
		linkedBlockingQueue = new ArrayBlockingQueue<Runnable>(4);
		threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
				keepAliveTime, TimeUnit.DAYS, linkedBlockingQueue,
				new ThreadPoolExecutor.CallerRunsPolicy());
	}

	/**
	 * @Title: work
	 * @Description: 从指定pom.xml文件获取地址
	 * @param @return
	 * @return ArrayList<String>
	 */
	public static ArrayList<String> work() {
		ArrayList<String> list = new ArrayList<String>();
		// TODO Auto-generated method stub
		Document document = null;
		try {
			document = Jsoup.parse(new File("pom.xml"), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Elements elements = document.select("dependency");
		//System.out.println(elements);
		for (int i = 0; i < elements.size(); i++) {
			String first = "";
			String[] firsts = elements.get(i).select("groupid").get(0).text()
					.split("\\.");
			for (int j = 0; j < firsts.length; j++) {
				first += firsts[j] + "/";
			}
			String second = elements.get(i).select("artifactid").get(0).text()
					+ "/";
			String third = elements.get(i).select("version").get(0).text()
					+ "/";
			if (third.contains("$")) {
				third = "";
			}

			list.add(first + second + third);
		}
		return list;
	}
}
